#!/usr/bin/env python3
"""
Stubs目录管理器

提供通用的stubs目录发现和初始化机制，将stubs目录添加到Python路径中。
各stub模块在被import时自行处理扩展注册。
"""

import sys
import os
from pathlib import Path
from typing import List, Optional, Dict, Any


class StubsManager:
    """Stubs目录管理器"""

    _instance: Optional["StubsManager"] = None
    _initialized: bool = False

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if not self._initialized:
            self._stubs_directories: List[str] = []
            self._default_stubs_path: Optional[str] = None
            self._initialized = True

    def configure(self, config: Optional[Dict[str, Any]] = None) -> None:
        """配置stubs目录

        Args:
            config: 编译器配置，包含stubs_directories配置项
        """
        # 清空之前的配置
        self._stubs_directories.clear()

        # 添加默认的stubs目录（项目根目录下的stubs）
        if self._default_stubs_path is None:
            self._default_stubs_path = self._find_default_stubs_path()

        if self._default_stubs_path and os.path.exists(self._default_stubs_path):
            self._stubs_directories.append(self._default_stubs_path)

        # 添加配置中指定的额外stubs目录
        if config and "compiler" in config:
            compiler_config = config["compiler"]
            extra_stubs = compiler_config.get("stubs_directories", [])
            for stub_dir in extra_stubs:
                stub_path = os.path.abspath(stub_dir)
                if (
                    os.path.exists(stub_path)
                    and stub_path not in self._stubs_directories
                ):
                    self._stubs_directories.append(stub_path)

    def _find_default_stubs_path(self) -> Optional[str]:
        """查找默认的stubs目录

        通过查找mcpy包的位置来确定项目根目录下的stubs目录
        """
        try:
            # 获取当前文件的路径
            current_file = Path(__file__).resolve()
            # 向上查找到mcpy项目根目录
            mcpy_root = current_file.parent.parent
            stubs_path = mcpy_root / "stubs"
            return str(stubs_path) if stubs_path.exists() else None
        except Exception:
            return None

    def initialize_stubs_paths(self) -> None:
        """初始化stubs目录到Python路径"""
        for stubs_dir in self._stubs_directories:
            if stubs_dir not in sys.path:
                sys.path.insert(0, stubs_dir)

    def get_stubs_directories(self) -> List[str]:
        """获取所有配置的stubs目录"""
        return self._stubs_directories.copy()


# 全局实例
_stubs_manager = StubsManager()


def configure_stubs(config: Optional[Dict[str, Any]] = None) -> None:
    """配置stubs目录

    Args:
        config: 编译器配置
    """
    _stubs_manager.configure(config)


def initialize_stubs() -> None:
    """初始化stubs目录到Python路径"""
    _stubs_manager.initialize_stubs_paths()


def get_stubs_directories() -> List[str]:
    """获取所有配置的stubs目录"""
    return _stubs_manager.get_stubs_directories()
